package com.ziyan.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.ziyan.pojo.ItemDoc;
import com.ziyan.pojo.RequestParam;
import com.ziyan.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class SearchServiceImpl implements SearchService , Serializable {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public Map<String, List<String>> filters(RequestParam params) {
        // 1.准备Request
        SearchRequest request = new SearchRequest("tb_item");
        // 2.准备DSL
        //2.1 query
        buildBasicQuery(params,request);
        //2.2 排序
        if("price".equals(params.getSortBy())){
            request.source().sort("price", SortOrder.ASC);
        }
        if("sold".equals(params.getSortBy())){
            request.source().sort("sold", SortOrder.DESC);
        }
        //2.3分页
        request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());
        //2.4聚合
        request.source().size(0);
        aggregation(request,params);
        // 3.发出请求
        SearchResponse response  = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 4.解析结果
        Map<String, List<String>> result = new HashMap<>();
        Aggregations aggregations = response.getAggregations();
        // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brand_agg");
            result.put("brand", brandList);
        // 4.2.根据分类名称，获取品牌结果
            List<String> categoryList = getAggByName(aggregations, "category_agg");
            result.put("category", categoryList);
        return result;

    }

    @Override
    public PageDTO<ItemDoc> list(RequestParam params) {
        // 1.准备Request
        SearchRequest request = new SearchRequest("tb_item");
        // 2.准备DSL
        //2.1 query
        buildBasicQuery(params,request);
        //2.2 排序
        if("price".equals(params.getSortBy())){
            request.source().sort("price", SortOrder.ASC);
        }
        if("sold".equals(params.getSortBy())){
            request.source().sort("sold", SortOrder.DESC);
        }
        //2.3分页
        request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());
        // 3.发出请求
        SearchResponse response  = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.解析响应
        return handleResponse(response);

    }


    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            //加入集合
            list.add(itemDoc);
        }
        PageDTO<ItemDoc> pageDTO = new PageDTO<>();
        pageDTO.setTotal(total);
        pageDTO.setList(list);
        return pageDTO;
    }

    private void buildBasicQuery(RequestParam params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 3.分类条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 4.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice()*100)
                    .lte(params.getMaxPrice()*100)
            );
        }
        // 7.放入source
        request.source().query(boolQuery);
    }

    private void aggregation(SearchRequest request, RequestParam params) {
            request.source().aggregation(
                    AggregationBuilders
                            .terms("category_agg")
                            .field("category")
                            .size(20));
            request.source().aggregation(
                    AggregationBuilders
                            .terms("brand_agg")
                            .field("brand")
                            .size(20));
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }
    @Override
    public void deleteById(Long id) {
        log.info("执行了删除操作");
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("tb_item", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Item item) {
        log.info("执行了新增、修改操作");
        try {
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);
            // 1.准备Request对象
            IndexRequest request = new IndexRequest("tb_item").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}